

import { remove } from "./utils"

type OPTIONS = {
  single?: boolean
}
type LOADING = {
  text?: string
  background?: string
}
export interface CLASLOADING {
  close(): void
  show(option?: LOADING): void
}
interface interDgLoad {
  loading(): CLASLOADING
  getInstance(): void
  close(item: CLASLOADING): void
  closeAll(): void
  addBackground(): void
  removeBackground(): void
}

class DgLoad implements interDgLoad {
  single = false
  bgEl?: HTMLElement
  instanceLoad?: CLASLOADING
  instances: CLASLOADING[] = []
  constructor(option?: OPTIONS) {
    if (option) {
      this.single = !!option.single as boolean
    }
  }
  loading(option?: LOADING) {
    let instance = this.getInstance()
    if (this.instances.indexOf(instance) == -1) {
      this.instances.push(instance)
      if (this.instances.length == 1) {
        this.addBackground();
      }
    }
    instance.show(option);
    return instance
  }
  getInstance(): CLASLOADING {
    let isNew = false
    if (!this.instanceLoad) {
      isNew = true
      this.instanceLoad = new loading(this)
    }
    if (this.single) {
      return this.instanceLoad
    } else {
      let instance = isNew ? this.instanceLoad : new loading(this)
      return instance
    }
  }
  close(item: CLASLOADING) {
    if (this.instances) {
      remove<CLASLOADING>(this.instances, item)
    }
    // if(this.single)
    if (!this.instances.length) {
      this.removeBackground()
    }
  }
  closeAll() {
    this.instances.map(el => el).forEach(el => el.close())
    this.instances = []
  }
  // 添加背景
  addBackground() {
    this.bgEl = createEl('dg__load__bg')
    document.body.appendChild(this.bgEl)
  }
  // 移除背景
  removeBackground() {
    if (this.bgEl) {
      document.body.removeChild(this.bgEl)
    }
  }

}




class loading implements CLASLOADING {
  htmlEl?: HTMLElement
  $parent: DgLoad
  statusNum?: 0 | 1   // 0： 休眠 1：执行中
  constructor(parent: DgLoad) {
    this.$parent = parent;
  }
  show(option?: LOADING) {
    if (this.statusNum == 1) return
    this.htmlEl = createEl('dg__load__wrap')
    let box = createEl('dg__load__box', 'p')
    box.appendChild(createEl('dg__load', 'span'))
    this.htmlEl.appendChild(box)
    let txt = ''
    if (option && option.text) {
      txt = option.text
    }
    this.htmlEl.appendChild(createEl('', 'p', txt))
    document.body.appendChild(this.htmlEl)
    this.statusNum = 1;
  }
  close() {
    if (this.statusNum == 0) return
    this.statusNum = 0;
    if (this.htmlEl) {
      document.body.removeChild(this.htmlEl)
    }
    this.$parent.close(this)
  }
}




function createEl(clas: string, tag?: string, txt?: string) {
  let el = document.createElement(tag || 'div')
  el.className = clas
  el.innerText = txt || ''
  return el
}

// let p = new DgLoad({ single: true })
export default DgLoad

